﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace NJL.WebManage
{
    public class BasePage : System.Web.UI.Page
    {
        public string WEBSITE_CODE = "";
        public string WEBSITE_NAME = "";
        public string USER_ID = "";
        public string USER_NAME = "";
        public string USER_TYPE = "2";//这个属于管理员后台用户，如果是1，说明是前台注册用户类型
        public string USER_TYPE_CODE = "2";
        public string USER_TYPE_NAME = "";

        public string UserStyle = "";

        public BasePage()
        {
            this.Load += new EventHandler(CheckUser);
            this.Load += new EventHandler(adDoCustomizeSetup);
        }

        /// <summary>
        /// 数据初始化
        /// </summary>
        public virtual void DataInit()
        {
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        public virtual void PageInit()
        {
        }

        /// <summary>
        /// 变量初始化
        /// </summary>
        public virtual void VariableInit()
        {
        }

        /// <summary>
        /// 校验登录用户
        /// </summary>
        private void CheckUser(object sender, EventArgs e)
        {
            //if (Session["websitecode"] == null)
            //{
            //    Session.Add("websitecode", "1");
            //}
            //if (Session["userid"] == null)
            //{
            //    Session.Add("userid","1");
            //}
            //if (Session["username"] == null)
            //{
            //    Session.Add("username","admin");
            //}

            //if (Request.Cookies["websitecode"] != null && Request.Cookies["userid"] != null && Request.Cookies["username"] != null && Request.Cookies["websitename"] != null && Request.Cookies["usertypename"] != null)
            if (Session["websitecode"] != null && Session["userid"] != null && Session["username"] != null && Session["websitename"] != null && Session["usertypename"] != null)
            {
                WEBSITE_CODE = Session["websitecode"].ToString();
                USER_ID = Session["userid"].ToString();
                USER_NAME = Session["username"].ToString();
                USER_TYPE_CODE = Session["usertypecode"].ToString();
                USER_TYPE_NAME = Session["usertypename"].ToString();
                WEBSITE_NAME = Session["websitename"].ToString();
            }
            else
            {
                Response.Redirect("~/Login.aspx");
            }
        }

        #region  判断当前用户是否拥有指定权限
        protected bool IsHasRoleAtom(string QXDM)
        {
            //foreach (string roles in UserRoles)
            //{
            //    if (roles == QXDM) return true;

            //}
            return false;
        }
        #endregion

        #region 格式化下属员工编号用于sql in
        private string FormatStrToSql(string XSYGBH)
        {

            string SqlXSYGBH = "";
            if (XSYGBH != "" && XSYGBH.IndexOf(",") > 0)
            {
                string[] BH = XSYGBH.Split(',');
                foreach (string tempBH in BH)
                {
                    SqlXSYGBH += ",'" + tempBH + "'";

                }
                SqlXSYGBH = SqlXSYGBH.Substring(1);

            }

            if (XSYGBH != "" && XSYGBH.IndexOf(",") < 0)
            {
                SqlXSYGBH += "'" + XSYGBH + "'";
            }
            if (XSYGBH == "") { SqlXSYGBH = "''"; }
            return SqlXSYGBH;


        }
        #endregion

        public void adDoCustomizeSetup(object sender, EventArgs e)
        {

            string strScript;
            string strStyleSheetsPath = this.Request.ApplicationPath + "Styles/Css/skin1.css";
            if (!string.IsNullOrEmpty(UserStyle))
            {
                strStyleSheetsPath = this.Request.ApplicationPath + "Styles/" + UserStyle + "";
            }
            // string strStyleSheetsPath1 = this.Request.ApplicationPath + "Admin/Styles/Style1/table.css";
            strScript = @"<link href=""" + strStyleSheetsPath + @""" type=""text/css"" rel=""stylesheet"">";
            if (!this.ClientScript.IsClientScriptBlockRegistered("adDoCustomizeSetup"))
                this.ClientScript.RegisterClientScriptBlock("".GetType(), "adDoCustomizeSetup", strScript);
        }


        #region 后台图片上传、读取、删除公共处理方法

        public string SaveUploadFile(HttpFileCollection ContractFile)
        {
            string strImageID = "";
            string strFileName = FileManageGetFileName();
            string strFileType = FileManageGetFileType(ContractFile);
            string strFileSavePath = FileManageGetFileUrlPath(WEBSITE_CODE, USER_TYPE);
            string strFileLocalPath = HttpContext.Current.Server.MapPath(strFileSavePath);
            //
            if (Royalsoft.Common.FileManage.SaveFile(ContractFile, strFileLocalPath, strFileName, strFileType))
            {
                BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();
                Model.NJL_IMAGE model = new Model.NJL_IMAGE();

                model.IMAGE_NAME = strFileName;
                model.IMAGE_TYPE = strFileType;
                model.IMAGE_URL_PATH = strFileSavePath;
                model.IMAGE_LOCAL_PATH = strFileLocalPath;
                model.IMAGE_FROM_TYPE = Convert.ToInt32(USER_TYPE);
                model.ID = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(111, 999).ToString();
                model.CREATE_USER_ID = USER_ID;
                model.CREATE_USER_NAME = USER_NAME;
                model.CREATE_DATE_TIME = System.DateTime.Now;

                bll.Add(model);

                strImageID = model.ID;
            }

            return strImageID;
            //
        }
        public string SaveUploadFile(HttpFileCollection ContractFile, int fileUploadIndex)
        {
            string strImageID = "";
            string strFileName = FileManageGetFileName();
            string strFileType = FileManageGetFileType(ContractFile, fileUploadIndex);
            string strFileSavePath = FileManageGetFileUrlPath(WEBSITE_CODE, USER_TYPE);
            string strFileLocalPath = HttpContext.Current.Server.MapPath(strFileSavePath);
            //
            if (Royalsoft.Common.FileManage.SaveFile(ContractFile, strFileLocalPath, strFileName, strFileType, fileUploadIndex))
            {
                BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();
                Model.NJL_IMAGE model = new Model.NJL_IMAGE();
                model.IMAGE_NAME = strFileName;
                model.IMAGE_TYPE = strFileType;
                model.IMAGE_URL_PATH = strFileSavePath;
                model.IMAGE_LOCAL_PATH = strFileLocalPath;
                model.IMAGE_FROM_TYPE = Convert.ToInt32(USER_TYPE);
                model.ID = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(111, 999).ToString();
                model.CREATE_USER_ID = USER_ID;
                model.CREATE_USER_NAME =USER_NAME;
                model.CREATE_DATE_TIME = System.DateTime.Now;
                bll.Add(model);
                strImageID = model.ID;
            }

            return strImageID;
            //
        }
        /// <summary>
        /// 获得文件的类型
        /// </summary>
        /// <param name="ContractFile"></param>
        /// <returns></returns>
        public string FileManageGetFileType(HttpFileCollection ContractFile, int fileUploadIndex)
        {
            string strFileType = "";
            if (ContractFile[fileUploadIndex].ContentLength > 0)
            {
                strFileType = ContractFile[fileUploadIndex].FileName.Substring(ContractFile[fileUploadIndex].FileName.LastIndexOf("."));
            }
            return strFileType;
        }
        /// <summary>
        /// 获得文件存储路径
        /// </summary>
        /// <param name="WebsiteCode">网站编号</param>
        /// <param name="UserType">用户类型：1：User，2：Admin</param>
        /// <returns></returns>
        public string FileManageGetFileUrlPath(string WebsiteCode, string UserType)
        {
            string strFileSavePath = "";
            DateTime dtime = DateTime.Now;

            strFileSavePath = System.Configuration.ConfigurationManager.AppSettings["UploadFileSavePath"] + "/" + WebsiteCode + "/" + UserType + "/" + dtime.ToString("yyyy") + "/" + dtime.ToString("MM") + "/" + dtime.ToString("dd") + "/";

            return strFileSavePath; 
        }

        /// <summary>
        /// 获得文件物理路径
        /// </summary>
        /// <param name="FileUrlPath">文件URL路径</param>
        /// <returns></returns>
        public string FileManageGetFileLocalPath(string FileUrlPath)
        {
            string strFileSavePath = "";
            DateTime dtime = DateTime.Now;

            strFileSavePath = System.Configuration.ConfigurationManager.AppSettings["UploadFileSavePath"] + "/" + WEBSITE_CODE + "/" + dtime.ToString("yyyy") + "/" + dtime.ToString("MM") + "/" + dtime.ToString("dd") + "/";

            return strFileSavePath;
        }

        /// <summary>
        /// 获得新文件名称
        /// </summary>
        /// <returns></returns>
        public string FileManageGetFileName()
        {
            return System.Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 获得文件的类型
        /// </summary>
        /// <param name="ContractFile"></param>
        /// <returns></returns>
        public string FileManageGetFileType(HttpFileCollection ContractFile)
        {
            string strFileType = "";
            if (ContractFile[0].ContentLength > 0)
            {
                strFileType = ContractFile[0].FileName.Substring(ContractFile[0].FileName.LastIndexOf("."));

                //strFileType = ContractFile[0].ContentType;
            }

            return strFileType;
        }

        /// <summary>
        /// 通过图片编号获取图片URL路径
        /// </summary>
        /// <param name="ImageCode"></param>
        /// <returns></returns>
        public static string GetImageUrl(string ImageCode)
        {
            BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();

            Model.NJL_IMAGE model = bll.GetModel(ImageCode);

            if (model != null)
            {
                return model.IMAGE_URL_PATH + model.IMAGE_NAME + model.IMAGE_TYPE;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 通过图片编号删除图片
        /// </summary>
        /// <param name="ImageCode"></param>
        /// <returns></returns>
        public bool DeleteImageByCode(string ImageCode)
        {
            BLL.NJL_IMAGE bll = new BLL.NJL_IMAGE();

            Model.NJL_IMAGE model = bll.GetModel(ImageCode);
            if (model != null)
            {
                if (Royalsoft.Common.FileManage.DeletePicture(model.IMAGE_URL_PATH + model.IMAGE_NAME + model.IMAGE_TYPE))
                {
                    return bll.Delete(ImageCode);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        #endregion
        #region SQL注入过滤
        /// <summary>
        ///SQL注入过滤
        /// </summary>
        /// <param name="InText">要过滤的字符串</param>
        /// <returns>如果参数存在不安全字符，则返回true</returns>
        public static bool SqlFilter(string InText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 页面调用短信发送接口

        public string SendSMS(string Mobile, string SMSContent)
        {
            //北京公司短信接口
            string i = SmsMD(Mobile, SMSContent);

            //int i = Royalsoft.Common.SMS.SendSMS(System.Configuration.ConfigurationManager.AppSettings["SMSSN"], Mobile, SMSContent, "5");

            return i;
        }

        /// <summary>
        /// 北京MD短信公司短信平台
        /// </summary>
        /// <param name="Mobile"></param>
        /// <param name="SMSContent"></param>
        /// <returns></returns>
        private string SmsMD(string Mobile, string SMSContent)
        {
            string SmsMD_SN = System.Configuration.ConfigurationManager.AppSettings["SMSMDSN"];
            string SmsMD_PWD = System.Configuration.ConfigurationManager.AppSettings["SMSMDPWD"];
            string SmsMD_Password = SmsMDgetMD5(SmsMD_SN + SmsMD_PWD);
            WebManage.sms.WebService sms = new WebManage.sms.WebService();

            string strValue = sms.mt(SmsMD_SN, SmsMD_Password, Mobile, SMSContent, "", "", "");

            return strValue;
        }
        /// <summary>
        /// 获取md5码------北京MD短信公司短信平台
        /// </summary>
        /// <param name="source">待转换字符串</param>
        /// <returns>md5加密后的字符串</returns>
        private string SmsMDgetMD5(string source)
        {
            string result = "";
            try
            {
                MD5 getmd5 = new MD5CryptoServiceProvider();
                byte[] targetStr = getmd5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(source));
                result = BitConverter.ToString(targetStr).Replace("-", "");
                return result;
            }
            catch (Exception)
            {
                return "0";
            }
        }
        #endregion
    }
}
